package br.ufc.vv.servlets;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import br.ufc.vv.controller.CmdAtualizarVotacao;
import br.ufc.vv.controller.CmdBuscarVotacao;
import br.ufc.vv.controller.CmdListarTodosUsuarios;
import br.ufc.vv.controller.CmdListarUsuariosParticipantesEleicoes;
import br.ufc.vv.controller.CmdListarVotacoes;
import br.ufc.vv.controller.CmdRemoverVotacao;
import br.ufc.vv.controller.Comando;


public class ServletCentral extends HttpServlet {

    private HashMap<String, Comando> comandos;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        session.removeAttribute("sucesso");
        session.removeAttribute("erro");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String cmd = request.getParameter("comando");
            System.out.println("Cmd:" + cmd);
        Comando comando = (Comando) comandos.get(cmd);
        try {
            String tela = comando.executar(request, response);
            if (tela != null && !tela.trim().equals("")) {
                response.sendRedirect(request.getContextPath() + tela);
                MDC.put("IP", request.getRemoteAddr());
                LoggerFactory.getLogger(this.getClass()).info("IP: " + request.getRemoteAddr());
                //LoggerFactory.getLogger(this.getClass()).info("Id do Perfil: " + statusConexao);
                LoggerFactory.getLogger(this.getClass()).info("Data e Horário: " + new Date().toString());
                LoggerFactory.getLogger(this.getClass()).info("Página: " + tela);
                LoggerFactory.getLogger(this.getClass()).info("Comando obitido da página: " + cmd);
                LoggerFactory.getLogger(this.getClass()).info("Comando executado: " + comando.getClass().getName());
            } else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
                MDC.put("IP", request.getRemoteAddr());
                LoggerFactory.getLogger(this.getClass()).error("IP: " + request.getRemoteAddr());
                //LoggerFactory.getLogger(this.getClass()).error("Id do Perfil: " + statusConexao);
                LoggerFactory.getLogger(this.getClass()).error("Data e Horário: " + new Date().toString());
                LoggerFactory.getLogger(this.getClass()).error("Página: " + tela);
                LoggerFactory.getLogger(this.getClass()).error("Comando obitido da página: " + cmd);
                LoggerFactory.getLogger(this.getClass()).error("Comando executado: " + comando.getClass().getName());
            }
        } catch (Exception e) {
            System.out.println("====:(");
            session.setAttribute("erro", "Usuário, senha e conta não conferem.");
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            MDC.put("IP", request.getRemoteAddr());
            MDC.put("Data e Horário", new Date().toString());
           // MDC.put("Id do Perfil", statusConexao);
            MDC.put("Comando obitido da página", cmd);
            MDC.put("Comando executado", comando.getClass().getName());
            LoggerFactory.getLogger(this.getClass()).error("error {}", this.getClass().getSimpleName(), e);
        }
    }

    @Override
    public void init() {
        Comando cmdo;
        comandos = new HashMap<String, Comando>();
        cmdo = new CmdListarTodosUsuarios();
        comandos.put("CmdListarTodosUsuarios", cmdo);
        cmdo = new CmdListarUsuariosParticipantesEleicoes();
        comandos.put("CmdListarUsuariosParticipantesEleicoes", cmdo);
        cmdo = new CmdAtualizarVotacao();
        comandos.put("CmdAtualizarVotacao", cmdo);
        cmdo = new CmdBuscarVotacao();
        comandos.put("CmdBuscarVotacao", cmdo);
        cmdo = new CmdListarVotacoes();
        comandos.put("CmdListarVotacoes", cmdo);
        cmdo = new CmdRemoverVotacao();
        comandos.put("CmdRemoverVotacao", cmdo);
        
            }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
